/*
This code is licenced under LGPL v3

Author : Alexandre Stanislawski
*/

/**
fadeImages

Simple jQuery plugin that can transform a div containing images into a slideshow with a fade as a transition.

In : 
- params : object containing the attributes :  
	- timeout : time before next transition
	- fadeDuration : transition duration
*/
jQuery.fn.fadeImages = function(params){
    var config = {
        timeout: 4000,
        fadeDuration: 500
    };
    if (params) jQuery.extend(config, params);

    function faderCreator(imgSet){
        var current = 0;
        var total = imgSet.size();
        
        var fader = function(){
            var nextIter = current + 1;
            if (nextIter >= total){
                nextIter = 0;
            }

            $(imgSet[current]).animate({
                opacity: 0
            }, params.fadeDuration);
                        
            $(imgSet[nextIter]).animate({
                opacity: 1
            }, params.fadeDuration, function(){
                setTimeout(fader, params.timeout);
            });
            
            current = nextIter;
          };
        return fader;
    }

    this.each(
    function(){
        jQthis = jQuery(this);
        jQthis.css({
            position: "relative",
            overflow: "hidden"
        });
        var imgSet = jQthis.find("img");
        imgSet.css({
            opacity: 0,
            position: "absolute",
            top: 0,
            left: 0
        });
        imgSet.first().css({
            opacity: 1
        });

        setTimeout(faderCreator(imgSet), params.timeout);
    });
    return this;
};
